package cn.zhfeat.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 
 * @author zhaoxin
 * 2017年12月29日 上午9:59:52
 */
public class CSVUtil {
	public static List<String> dealCSV(String lineStr){
		List<String> result = new ArrayList<String>();
		
		lineStr = lineStr.replaceAll(",\"\"\"", ",\"!@#%''!@#%");
		lineStr = lineStr.replaceAll("\"\"\",", "!@#%''!@#%\",");
		if(lineStr.subSequence(1, 4).equals("\"\"\"")) {
			lineStr = "\"!@#%''!@#%"+lineStr.substring(4);
		}
		if(lineStr.endsWith("\"\"\"")) {
			lineStr = lineStr.substring(0,lineStr.length()-3)+"!@#%''!@#%\"";
		}
		lineStr = lineStr.replace(",\"\"", ",!@#%''!@#%");
		lineStr = lineStr.replace("\"\",", "!@#%''!@#%,");
		
		Pattern pattern = Pattern.compile("\"[^\"]*\"");
		Matcher matcher = pattern.matcher(lineStr);
		List<String> list = new ArrayList<String>();
		while(matcher.find()) {
			String group = matcher.group();
			list.add(group);
		}
		
		String[] split = lineStr.split(",");
		for(int i=0; i<split.length; i++) {
			String s1 = split[i];
			int isAdd = 0;
			for (String s2 : list) {
				if(s2.contains(s1)) {
					String s3 = "";
					int j = i;
					while(true) {
						s3 += ","+split[j++];
						if(s3.length() >= s2.length()) {
							break;
						}
					}
					s3 = s3.substring(1);
					if(s2.equals(s3)) {
						i=--j;
						result.add(s3.substring(1,s3.length()-1).replaceAll("!@#%''!@#%", "\""));
						isAdd++;
						break;
					}
				}
			}
			if(isAdd==0) {
				result.add(s1.replaceAll("!@#%''!@#%", "\""));
			}
		}
		return result;
	}
}